/*
 *  后台管理页面，进行系统设置和用户信息，题目信息的导入
 */
var os = require('os');
var express = require('express');
var mongoose = require('mongoose');
var url = require('url');
var querystring = require('querystring');
var path = require('path');
var fs = require('fs');
var iconv = require('iconv-lite');
var moment = require('moment');
var fileutil = require('../models/fileutil');
var Setting = require('../models/setting.js');
var Store = mongoose.model('Store');

var async = require('async');

//上传相关的中间键
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var formater = 'YYYY-MM-DD HH:mm:ss';

//服务层
var UserService = require('./service/userService.js');
var CategoryService = require('./service/categoryService.js');
var StoreService = require('./service/storeService.js');
var QuestionService = require('./service/questionService.js');
var ReportService = require('./service/reportService.js');

var router = express.Router();

router.get('/', function(req, res){
    console.log('admin index');
    res.render('admin/index', {
        Setting : Setting.getData()
    });
});

router.get('/settings', function(req, res) {
    res.render('settings', {
        Setting : Setting.getData()
    });
});

router.post('/settings', function(req, res) {
    console.log('admin后台setting请求');
    var SettingService = require('./service/settingService.js');
    new SettingService().saveData(req.body);
    res.redirect('/admin');
});

router.get('/user', function(req, res) {
    console.log('admin user');
    var userService = new UserService();
    userService.getAllProfession(function (err, types) {
        res.render('admin/user', {
            professions: types.join('、')
        });
    })
});

router.post('/user', function (req, res) {
    console.log(req.body);
    var userService = new UserService();
    userService.getAllUser(null, null, {
        num: parseInt(req.body.page),
        limit: parseInt(req.body.limit)
    }, null, {
        sid: 1 //排序 1正序 -1倒叙
    }, function (err, currentPage, count, limit, pageCount, result) {
        if(err) throw err;
        res.send({
            result: result,
            count: count,
            pageCount: pageCount,
            currentPage: currentPage,
            limit: limit
        });
    });
});

//上传用户
router.post('/uploaduser', multipartMiddleware, function (req, res) {
    var userService = new UserService();
    var path = req.files.usercsv.path;
    if (path) {
        userService.uploadUser(path, 'utf-8');
    }
    res.redirect('/admin/user');
});

//更新用户
router.post('/updateUser', function (req, res) {
    console.log("update User");
    var userService = new UserService();
    var name = req.body.name;
    var profession = req.body.profession;
    var sid = req.body.sid;
    var params = {};
    if(profession){
        params['profession'] = profession || '';
    } else {
        params['name'] = name || '';
    }
    userService.updateUser(params, {
        sid: sid
    }, function (err, data) {
        if (err)throw err;
        res.send(data);
    })
});

//获取分类
router.post('/category', function (req, res) {
    var cid = req.body.cid; //当前ID
    var cateService = new CategoryService();
    cateService.loadData(cid, function (err, data) {
        if(err) throw err;
        res.send(data);
    });
});

/**
 * 增加一个分类
 */
router.post('/addCategory', function (req, res) {
    var pid = req.body.pid; //当前ID
    var cateService = new CategoryService();
    cateService.addNode(pid, function (err, data) {
        if(err) throw err;
        res.send(data);
    })
});

/**
 * 移除一个分类
 */
router.post('/removeCategory', function (req, res) {
    var cid = req.body.cid; //当前ID
    var cateService = new CategoryService();
    cateService.removeNode(cid, function (err, data) {
        if(err) throw err;
        res.send(data);
    })
});

/**
 * 重命名分类
 */
router.post('/renameCategory', function (req, res) {
    var cid = req.body.cid; //当前ID
    var text = req.body.text;
    var cateService = new CategoryService();
    cateService.renameNode(cid, text, function (err, data) {
        if(err) throw err;
        res.send(data);
    })
});

//题集管理
router.get('/store', function (req, res) {
    var userService = new UserService();
    userService.getAllProfession(function (err, types) {
        res.render('admin/store', {
            professions: types.join('、')
        });
    })
});


router.post('/store', function (req, res) {
    console.log(req.body);
    var storeService = new StoreService();
    storeService.getAllStore({
        active: true
    }, {
        path: 'category bestUser'
    },{
        num: parseInt(req.body.page),
        limit: parseInt(req.body.limit)
    }, null, null, function (err, currentPage, count, limit, pageCount, result) {
        if(err) throw err;
        res.send({
            result: result,
            count: count,
            pageCount: pageCount,
            currentPage: currentPage,
            limit: limit
        });
    });
});


//更新题库
router.post('/updateStore', function (req, res) {
    console.log("update Store");
    var storeService = new StoreService();
    var sid = req.body.sid;
    var profession = req.body.profession;
    var drill = req.body.drill;
    var score = req.body.score;
    var duration = req.body.duration;

    storeService.updateStore({
        profession: profession,
        drill: parseInt(drill) || 0,
        score: parseInt(score) || 0,
        duration: parseInt(duration) || 60
    }, {
        _id: sid
    }, function (err, data) {
        if (err)throw err;
        res.send(data);
    })
});

//更新题库
router.post('/hideStore', function (req, res) {
    console.log("update hide");
    var storeService = new StoreService();
    var sid = req.body.sid;

    storeService.hideStore({
        active: false
    }, {
        _id: sid
    }, function (err, data) {
        if (err)throw err;
        res.send(data);
    })
});

//上传题集
router.post('/uploadstore', multipartMiddleware, function (req, res) {
    var storeService = new StoreService();
    var path = req.files.storeFile.path;

    var content = {};
    content['category'] = req.body.cateType;;
    content['text'] = req.body.text;
    content['drill'] = req.body.drill;
    content['score'] = req.body.score;
    content['duration'] = req.body.duration;
    var multiple = req.body.multiple;
    var single = req.body.single;
    var judge = req.body.judge;

    storeService.saveStore(content, function (err, store) {
        if(err) throw err;
        fs.readFile(path,{encoding:'binary'}, function(err, content) {
            if(err) throw err;
            var buf = new Buffer(content, 'binary');
            var content = iconv.decode(buf, 'GBK');
            var questions = content.split('\n');
            var qs = [];
            for(var i= 1,len=questions.length;i<len;i++){
                var questionArr = questions[i].split(',');
                if(questionArr.length < 11){
                    continue;
                }
                var q = {};
                q['store'] = store;
                q['score'] = Setting.get('score');
                if(!questionArr[1]){
                    continue;
                }
                q['text'] = questionArr[1]//
                var ops = [];
                if(questionArr[2]){//A
                    ops.push({
                        idx: 'A',
                        text: questionArr[2]
                    });
                }
                if(questionArr[3]){//B
                    ops.push({
                        idx: 'B',
                        text: questionArr[3]
                    });
                }
                if(questionArr[4]){//C
                    ops.push({
                        idx: 'C',
                        text: questionArr[4]
                    });
                }
                if(questionArr[5]){//D
                    ops.push({
                        idx: 'D',
                        text: questionArr[5]
                    });
                }
                if(questionArr[6]){//E
                    ops.push({
                        idx: 'E',
                        text: questionArr[6]
                    });
                }
                if(questionArr[7]){//F
                    ops.push({
                        idx: 'F',
                        text: questionArr[7]
                    });
                }
                if(questionArr[8]){//G
                    ops.push({
                        idx: 'G',
                        text: questionArr[8]
                    });
                }
                if(questionArr[9]){//H
                    ops.push({
                        idx: 'H',
                        text: questionArr[9]
                    });
                }
                q['opts'] = ops;
                q.answer = [];
                var answer = questionArr[10];
                answer = answer.replace(/\r|' '/gi, '') + '';
                answer = answer.toUpperCase();
                answer = answer.split('');
                q.answer = q.answer.concat(answer);
                qs.push(q);
            }
            /*for(var i= 0,len=content.length;i<len;i++){
                content[i]['store'] = store;
                if(!content[i]['score']){ //如果没有分数,就用默认的系统分数
                    content[i]['score'] = Setting.get('score');
                }
                var opts = content[i]['opts'];
                var newOpts = [];
                for (var key in opts) {
                    if(!key){
                        throw new Error('上传的题目文件似乎有问题,请检查');
                    }
                    newOpts.push({
                        idx: key.toUpperCase(),
                        text: opts[key]
                    });
                }
                content[i]['opts'] = newOpts;
            }*/

            //题目保存
            storeService.batchSaveQuestion(qs, function(err, questions){
                if(err) throw err;
                storeService.savePaper(store, questions, multiple, single, judge, function(err, paper){
                    if(err) throw err;
                });
            });
        });
    });

    res.redirect('/admin/store');
});

//题集管理
router.get('/question', function (req, res) {
    var store = req.query.sid;
    if(!store){
        res.redirect('/admin/store');
        return;
    }
    Store.findById(store, function(err, data){
        if(err) throw new Error('该题集不存在,或已经被删除');
        res.render('admin/question', {
            store: store,
            text: data.get('text')
        });
    })
});


router.post('/question', function (req, res) {
    var questionService = new QuestionService();
    var store = req.body.store;
    if(!store){
        res.redirect('/admin/store');
        return;
    }
    questionService.getAllQuestionByStore({
        store: store
    }, null ,{
        num: parseInt(req.body.page),
        limit: parseInt(req.body.limit)
    }, null, null, function (err, currentPage, count, limit, pageCount, result) {
        if(err) throw err;
        res.send({
            result: result,
            count: count,
            pageCount: pageCount,
            currentPage: currentPage,
            limit: limit
        });
    });
});

//更新题库
router.post('/updateQuestion', function (req, res) {
    console.log("updateQuestion");
    var questionService = new QuestionService();
    var qid = req.body.qid;
    var text = req.body.text;
    var answer = req.body.answer;
    var score = req.body.score;

    questionService.updateQuestion(qid, {
        text: text || '',
        answer: answer || [],
        score: parseInt(score) || 0
    }, function (err, data) {
        if (err)throw err;
        res.send(data);
    })
});

//导出
router.get('/report', function (req, res) {
    res.render('admin/report');
});

//对战导出
router.get('/report/battle', function (req, res) {
    var sid = req.query.sid;
    var pf = os.platform().toString();
    var filepath =  __dirname + (pf == 'win32' ? '\\' : '/')
        + (new Date()).getTime() + Math.random() + '.csv';

    var reportService = new ReportService();
    reportService.reportUserBattle(sid, function(err, data){
        if(err) throw err;
        var str = '题集名,创建人,创建时间,开始时间,结束时间,参战人,逃跑人\n' + data;

        fs.writeFile(filepath, str, {encoding:'UTF-8'}, function(){
            fileutil.download(req, res, filepath, '用户挑战记录.csv', function(err){
                if(err){
                    throw err;
                }
                fs.unlink(filepath);
            });
        });
        //res.render('admin/report');
    });

});

//题库导出
router.get('/report/store', function (req, res) {
    var pf = os.platform().toString();
    var filepath =  __dirname + (pf == 'win32' ? '\\' : '/')
        + (new Date()).getTime() + Math.random() + '.csv';

    var reportService = new ReportService();
    reportService.reportBattle(function(err, data){
        if(err) throw err;
        var str = '题集名,创建人,创建时间,开始时间,结束时间,参战人,逃跑人\n' + data;

        fs.writeFile(filepath, str, {encoding:'UTF-8'}, function(){
            fileutil.download(req, res, filepath, '题库挑战记录.csv', function(err){
                if(err){
                    throw err;
                }
                fs.unlink(filepath);
            });
        });
        //res.render('admin/report');
    });
});

//系统登录导出
router.get('/report/system', function (req, res) {
    Log.find().exec(function(err, logs){
        var pf = os.platform().toString();
        var filepath =  __dirname + (pf == 'win32' ? '\\' : '/')
            + (new Date()).getTime() + Math.random() + '.csv';

        var str = 'SID,用户,操作,时间\n';
        for(var i = 0, len = logs.length; i < len; i++){
            var l = logs[i];
            str += l.sid + ',' + l.name + ',' + l.action + ',' + moment(l.time).format(formater) + '\n';
        }
        fs.writeFile(filepath, str, {encoding:'UTF-8'}, function(){
            fileutil.download(req, res, filepath, '日志.csv', function(err){
                if(err){
                    throw err;
                }
                fs.unlink(filepath);
            });
        });
    });
});

//导出用户模版
router.get('/report/userTemplate', function (req, res) {
    console.log('导出用户模版');
    var pf = os.platform().toString();
    var split = (pf == 'win32' ? '\\' : '/');
    var filepath = path.normalize(__dirname + split + '..') + split + 'doc' + split + 'user.csv';
    fileutil.download(req, res, filepath, '用户模版.csv', function(err){
        if(err){
            throw err;
        }
    });
});

//导出题集模版
router.get('/report/questionTemplate', function (req, res) {
    console.log('导出题集模版');
    var pf = os.platform().toString();
    var split = (pf == 'win32' ? '\\' : '/');
    var filepath = path.normalize(__dirname + split + '..') + split + 'doc' + split + 'questions.csv';
    fileutil.download(req, res, filepath, '题集模版.csv', function(err){
        if(err){
            throw err;
        }
    });
});



module.exports = router;